<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <!-- 进度条组件 -->
    <el-progress v-if="progressShow" type="circle" :percentage="percentage" class="progress" />
  </el-upload>

</template>
<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDgBQO5VeW7QSDhtp1wZw3uUmoY1DDwOZT',
  SecretKey: 'e29zZsuf9MIxLUNzLQHsCG3ZomUu3wYu'
})
export default {
  data() {
    return {
      imageUrl: '', // 传入的图片
      progressShow: false, // 进度条默认不显示
      percentage: ''// 进度条进度的数值
    }
  },
  methods: {
    upload(res) {
      if (res.file) {
        // 让进度条显示
        this.progressShow = true
        cos.putObject({
          Bucket: 'ylh-1306621534', // 存储桶的名称，必须
          Region: 'ap-beijing', // 存储桶所在地域，必须字段
          Key: res.file.name, // 文件名，必须
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => { // 进度条
            console.log(progressData)
            this.percentage = progressData.percent * 100
          }
        }, (err, data) => { // 上传成功的回调
          // console.log(err || data)
          if (err === null && data.statusCode === 200) {
            this.imageUrl = 'https:' + data.Location
            // 成功时再让进度条隐藏
            this.progressShow = false
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
